<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/24
 * Time: 11:58
 */

namespace app\api\service;


use app\api\model\Banner;
use app\api\model\Category;
use app\api\model\Clickip;
use app\api\model\Openip;
use app\api\model\Product;
use app\api\model\UserTrue;
use app\lib\exception\MysqlErrorException;
use app\lib\exception\ParameterException;
use app\lib\exception\RedisServiceException;
use Driver\Cache\Redis;
use think\facade\Request;

class LqbService
{
    # 还差排序，重复出现
    public function showAll()
    {
        $allBanner = $this->getAllBanner();
        $allGrade = $this->getAllGrade();
        $allCategory = $this->getAllCategory();
        return array(
            'banner' => $allBanner,
            'grade' => $allGrade,
            'category' => $allCategory
        );
    }
    # 获取所有轮播图
    private function getAllBanner()
    {
        $model = new Banner();
        $result = $model->where('status','=',1)
            ->visible(['banner_url','img_url'])
            ->select();
        if($result == false){
            throw new MysqlErrorException([
               'code' => 500,
               'msg' => '服务器异常'
            ]);
        }
        return $result;
    }
    # 获取所有推广等级
    private function getAllGrade()
    {
        $model = new Product();
        $allProduct = $model->where('status','=',1)
            ->order('px','asc')
            ->visible(['product_id','title','img_url','price_min','price_max','limit_time','day_interest','application'])
            ->select();
        $first = array();
        $second = array();
        $third = array();
//        $repeat = array();
        foreach ($allProduct as $value){
            if($value['grade'] == 'A'){
                array_push($first, $value);
            }
            if($value['grade'] == 'B'){
                array_push($second, $value);
            }
            if($value['grade'] == 'C'){
                unset($value['application']);
                array_push($third, $value);
            }
//            if($value['repeat'] == 1){
//                array_push($repeat, $value);
//            }
        }
//        $arr = $this->addFirst($third, $repeat);

        # A等级栏目的部位（当A等级小于4的时候触发）
        if(count($first) < 4){
            $num = 4 - count($first);
            $third_count = count($third);
            for ($i = 0; $i <$num; $i++){
                if($third_count>=$num){
                    #
                    array_push($first, $third[$i]);
                }else{
                    if($third_count>0){
                        array_push($first, $third[$i]);
                        $third_count --;
                    }
//                    else{
//                        array_push($first, $second[$i]);
//                    }
                }
            }
        }
        if(count($second) < 8){
//            $in_first_id = [];
//            foreach ($first as $list){
//                if($list['grade'] == 'C'){
//                    array_push($in_first_id, $list['product_id']);
//                }
//            }

            $num = 8 - count($second);
            if(empty($third) == false){
                for ($i = 0; $i <$num; $i++){
                    array_push($second, $third[$i]);
                }
            }
        }
        return array(
            'first' => $first,
            'second' => $second,
            'third' => []
        );
    }
    # 获取所有分类等级
    private function getAllCategory()
    {
        $model = new Category();
        $result = $model->where('status','=',1)
            ->visible(['category_id','img_url'])
            ->select();
        if($result == false){
            throw new MysqlErrorException([
                'code' => 500,
                'msg' => '服务器异常'
            ]);
        }
        return $result;
    }
    # 查询单个产品的详情
    public function getOneProduct($id)
    {
        $model = new Product();
        $this->set_product_click($id);
        # 首先判断redis有没有值
        $redis_product_key = config('redis.product').$id;
        if(Redis::FindKeys($redis_product_key) == 1){
            $redis_product = Redis::hget($redis_product_key);
            return array(
              'in' => 'redis',
              'data' => $redis_product
            );
        }else {
            # redis不存在则给redis赋值
            $result = $model->where('product_id', '=', $id)
                ->hidden(['category_id', 'grade', 'px', 'add_time', 'up_time', 'bg_url'])
                ->find();
            if ($result == false) {
                throw new ParameterException([
                    'code' => 401,
                    'msg' => '商品不存在'
                ]);
            }
            if (($result->toArray())['status'] == 0) {
                throw new ParameterException([
                    'code' => 400,
                    'msg' => '商品已下架'
                ]);
            }
            unset($result['status']);
            # 同步写入redis
            Redis::hMset($redis_product_key, $result->toArray());
            # 设置key过期时间
            Redis::setKeyTime($redis_product_key, 86400);
            # 写入set集合中
            Redis::sAdd(config('redis.set_all_product'), $id);

            return array(
                'in' => 'mysql',
                'data' => $result
            );
        }

    }

    public function getCategoryProduct($category_id)
    {
        $model = new Product();
        $result = $model->where('category_id','=',$category_id)
            ->where('status','=',1)
            ->visible(['product_id','title','img_url','price_min','price_max','limit_time','day_interest'])
            ->select();
        if($result == false){
            throw new MysqlErrorException([
                'code' => 500,
                'msg' => '服务器异常'
            ]);
        }
        return $result;
    }

    public function getProductPage($page, $limit)
    {
        $new_page = $page-1;
        $model = new Product();
        $lists= $model->where('status','=', 1)
            ->order(['grade'=>'desc', 'px' => 'desc'])
            ->visible(['product_id','title','img_url','price_min','price_max','limit_time','day_interest','grade','px'])
            ->page($new_page, $limit)
            ->select()
            ->toArray();
        if(empty($lists)){
            return [
              'code' =>200,
              'msg' => '没有更多数据'
            ];
        }
        return array([
            'code' => 200,
            'data' => $lists,
            'msg' => "第{$page}页"
        ]);
    }
    # 拼接数组
    private function addFirst($third,$repeat)
    {
        $third_count = count($third);
        if($third_count - 5 <= 0){
            $new_repeat = array_slice($repeat,0,5-$third_count);
            $arr = array_merge($third, $new_repeat);
            return $arr;
        }else{
            $new_third = array_slice($third,0,5);
            return $new_third;
        }
    }
    # 记录前端申请按钮的次数，并写入redis-hash自增
    public function writeRecordToRedis($id)
    {
        $this->check_id_status($id);
        $bool = $this->open_ip($id);
        if($bool == false){
            try{
                $redis_hash_key = config('redis.open');
                Redis::hincrby($redis_hash_key, $id);
                return ['code' => 200];
            }catch (\Exception $e){
                throw new RedisServiceException();
            }
        }
    }

    # 打开产品自增1
    private function set_product_click($id)
    {
        # 检查id是否合法
        $this->check_id_status($id);
        # 检查当天的ip是否存在
        $bool = $this->click_ip($id);
        if($bool == false){
            try{
                $redis_hash_key = config('redis.click');
                Redis::hincrby($redis_hash_key, $id);
                return ['code' => 200];
            }catch (\Exception $e){
                throw new RedisServiceException();
            }
            return ;
        }
        return ;
    }

    # 判断产品id是否存在
    private function check_id_status($id)
    {
        $redis_set_key = config('redis.ids');
        $bool = Redis::sismember($redis_set_key, $id);
        if(!$bool){
            throw new ParameterException();
        }
    }

    # admin_click_ip 记录每个点击的IP和点击数
    private function click_ip($product_id)
    {
        $model = new Clickip();
        $bool = $this->find_today_ip($product_id, $model);
        return $bool;
    }

    # admin_open_ip 记录每个点击的IP和点击数
    private function open_ip($product_id)
    {
        $model = new Openip();
        $bool = $this->find_today_ip($product_id, $model);
        return $bool;
    }

}